#include "main_manager.h"
#include <QApplication>
#include <QMutex>
#include <QFile>
#include <QDateTime>
#include <QTextStream>

// 全局互斥锁保证线程安全
QMutex logMutex;


void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    QMutexLocker locker(&logMutex);  // 自动加锁/解锁

    QFile logFile("./app_log.txt");
    if (!logFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) {
        return;
    }

    QTextStream out(&logFile);
    out << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz") << " | ";

    switch (type) {
    case QtDebugMsg:
        out << "DEBUG | "; break;
    case QtInfoMsg:
        out << "INFO  | "; break;
    case QtWarningMsg:
        out << "WARN  | "; break;
    case QtCriticalMsg:
        out << "ERROR | "; break;
    case QtFatalMsg:
        out << "FATAL | ";
        logFile.close();
        abort();
    }

    out << msg << " (" << context.file << ":" << context.line << ")\n";
    logFile.close();  // 确保每次写入后刷新
}

int main(int argc, char *argv[])
{
    //用于在程序运行时设置环境变量
    //minimal仅提供最基本的事件循环和输入处理能力,不会显示任何窗口或图形界面
    qputenv("QT_QPA_PLATFORM", "minimal");

    qInstallMessageHandler(myMessageOutput);

    QApplication a(argc, argv);

    MainManager w;

    return a.exec();
}
